<?php
namespace app\index\domain;

class Classes
{
    private static $_objList = [];
    //缓存片段中的数据是否发生了变化
    private static $_hasChange = 0;
    private static $_record = null;

    /**
     * 获取某个对象
     */
    public static function get($type, $param=null)
    {
        $cacheKey = md5(serialize($param));
        if(!isset(self::$_objList[$type][$cacheKey]))
            self::$_objList[$type][$cacheKey] = self::create($type, $param);
        if(isset(self::$_objList['origin'][$type][$cacheKey]))
            self::$_objList[$type][$cacheKey] = self::$_objList['origin'][$type][$cacheKey];
        if(is_array(self::$_record))
            self::$_record[$type][$cacheKey] = self::$_objList[$type][$cacheKey];
        return self::$_objList[$type][$cacheKey];
    }

    /**
     * 创建某个对象
     */
    public static function create($type, $param=null)
    {
        $type = "\\app\\index\\domain\\".$type;
        if(!is_null($param))
            $obj = new $type($param);
        else
            $obj = new $type;
        return $obj;
    }

    /**
     * 存储数据对象
     */
    public static function cacheSave($cacheKey, $cacheList)
    {
        G('cacheSaveStart');
        unset($cacheList['TermList']);
        unset($cacheList['Term']);
        $cacheStr = serialize($cacheList);
        //$cacheStr = gzencode($cacheStr, 3);
        G('cacheSaveEnd');
        $cacheKey = $cacheKey.serialize(I('get.'));
        \think\Cache::set($cacheKey, $cacheStr, 3600);
        $logStr = '压缩并写入缓存对象，用时:'.G('cacheSaveStart','cacheSaveEnd');
        \think\Log::log($logStr);
    }

    /**
     * 取出缓存的数据对象
     */
    public static function cachePop($cacheKey)
    {
        //$cacheKey = $cacheKey.serialize(I('get.'));
        if(empty($cacheKey)) return false;
        $cacheStr = \think\Cache::get($cacheKey);
        if(empty($cacheStr)) return false;
        G('cachePopStart');
        //$cacheStr = gzdecode($cacheStr);
        $cacheList = unserialize($cacheStr);
        G('cachePopEnd');
        $logStr = '取出并解压缓存对象，用时:'.G('cachePopStart','cachePopEnd');
        \think\Log::log($logStr);
        return $cacheList;
    }

    /**
     * 缓存区域开始
     */
    public static function cacheStart($cacheKey, $unique=false)
    {
        if($unique)
            $cacheKey = $cacheKey.serialize(I('get.'));
        $cacheList = self::cachePop($cacheKey);
        if(!$cacheList){
            self::$_record = [];
            return;
        }
        $cacheList['origin'] = self::$_objList;
        self::$_objList = $cacheList;
    }

    /**
     * 缓存区域结束
     */
    public static function cacheEnd($cacheKey, $unique=false)
    {
        if($unique)
            $cacheKey = $cacheKey.serialize(I('get.'));
        if(is_array(self::$_record)){
            self::cacheSave($cacheKey, self::$_record);
        }else{
            self::$_objList = self::$_objList['origin'];
        }
    }
}

